package club.baimahu.pencil.miaosha.mybatis;


import club.baimahu.pencil.miaosha.mapper.*;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

/**
 * TODO
 *
 * @author zhanghongjiang
 * @version 1.0
 * @date 2021/9/13 15:53
 */
public class MapperFactory<T> {


    public static SqlSession getSqlSession(){
        TransactionFactory transactionFactory = new JdbcTransactionFactory();

        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc://localhost:3306/miaosha?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT";
        String username = "root";
        String password = "root123";
        PooledDataSource dataSource = new PooledDataSource(driver,url,username,password);

        Environment environment = new Environment("test", transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(StockMapper.class);

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        SqlSession sqlSession = sqlSessionFactory.openSession();

        return sqlSession;

    }

    public  static <T> T getMapper(Class<T> clazz){
        SqlSession sqlSession = getSqlSession();
        return sqlSession.getMapper(clazz);
    }
}
